package com.ophiux.controller;

import java.io.File;

import org.apache.commons.io.FilenameUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public class ImageFormatConverter {
     private static Logger logger = LoggerFactory.getLogger(ImageFormatConverter.class);
	
    public static boolean convertToWebp(String inputFile, String outputFile) {
        return convertToWebp(inputFile, outputFile, 50);
    }

    public static boolean convertToWebp(String inputFile, String outputFile, Integer quality) {
        if (!new File(inputFile).exists()) {
            return false;
        }

        String outputPath = FilenameUtils.getFullPath(outputFile);
        if (!new File(outputPath).exists()) {
            new File(outputPath).mkdirs();
        }

        return executeCWebp(inputFile, outputFile, quality);
    }

    private static boolean executeCWebp(String inputFile, String outputFile, Integer quality) {
        boolean result = false;
        String cwebpPath = "";
        try {
        	String way = "2";
			if("1".equals(way)) {
				//tomcat 空间时使用
				cwebpPath = ImageFormatConverter.class.getResource("").getPath().split("WEB-INF")[0]+"\\WEB-INF\\lib\\cwebp.exe";
				logger.info("tomcat下，cwebp.exe路径："+cwebpPath);
			}else if("2".equals(way)) {
				//eclipse 空间时使用
				cwebpPath = ImageFormatConverter.class.getResource("").getPath()+"cwebp.exe";
				logger.info("eclipse下，cwebp.exe路径："+cwebpPath);
			}
        	
			/**
			 * cwebp xxx.png  -lossless -o xxx.webp  //无损格式
				cwebp -q 100 xxx.png -o xx.webp //0-100质量范围
			 */
            StringBuilder command = new StringBuilder(cwebpPath);
            command.append(" -q " + (quality == 0 ? 75 : quality));
            command.append(" " + inputFile);
            command.append(" -o " + outputFile);

            Runtime.getRuntime().exec(command.toString());//执行命令

            result = true;
        } catch (Exception e) {
        	e.printStackTrace();
        	logger.info("加载cwebp.exe异常，异常信息：",e);
        }
        return result;
    }

    public static void main(String[] args) {
        String inputFile = "C:\\Users\\Administrator\\Desktop\\1.jpg";
        String outputFile = "C:\\Users\\Administrator\\Desktop\\1.webp";
        if (executeCWebp(inputFile, outputFile, 70)) {
            System.out.println("convert ok~");
        } else {
            System.out.println("sth wrong happened");
        }
    }
    
    public static boolean convertToWebp(String inputFile) {
    	String outputFile = inputFile.split("\\.")[0] + ".webp";
    	return convertToWebp(inputFile, outputFile, 75);
	}
}
